import type { UserInfo } from '@/composables/types/userInfo'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref<string | null>(null)
  const tokenExpire = ref<number>(0)
  const userInfo = ref<UserInfo | null>(null) // 您可以定义更具体的类型

  // 用户名密码登录
  async function login(username: string, password: string, code?: string): Promise<void> {
    console.log('执行登录操作', { username, password, code })
    const res = await Apis.post('/weixin/login', {
      username,
      password,
      code,
    })

    token.value = res.token
    tokenExpire.value = res.expire
    userInfo.value = res.user

    // 设置权限信息
    const permissionStore = usePermissionStore()
    permissionStore.setMenuList(res.user.menus || [])
    permissionStore.setRoleList(res.user.roles || [])

    useGlobalToast().success('登录成功')
  }

  // 使用微信code自动登录
  async function loginWithCode(code: string): Promise<void> {
    console.log('执行微信自动登录操作', { code })
    const res = await Apis.post('/weixin/loginByCode', {
      code,
    })

    token.value = res.token
    tokenExpire.value = res.expire
    userInfo.value = res.user

    // 设置权限信息
    const permissionStore = usePermissionStore()
    permissionStore.setMenuList(res.user.menus || [])
    permissionStore.setRoleList(res.user.roles || [])
  }

  // 退出登录
  async function logout() {
    // await Apis.get('/weixin/logout')
    token.value = null
    userInfo.value = null
  }

  return {
    token,
    tokenExpire,
    userInfo,
    login,
    loginWithCode,
    logout,
  }
})
